#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    # import pymel.core as pm
    import JTK.jmaya.core as jmc

except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class RemoveUnusedNodes(CheckBase):
    def __init__(self):
        super(RemoveUnusedNodes, self).__init__()
        pass

    def optimize_maya(self):
        NoDagNodes = []
        DefualtNodes = cmds.ls(dn=1)
        DagNodes = cmds.ls(dag=1)
        for node in cmds.ls(dep=1):
            if node not in DagNodes:
                NoDagNodes.append(node)

        used_nodes = []
        mesh_nodes = []
        for mesh_shape_node in cmds.ls(type="mesh"):
            mesh_nodes.append(cmds.listRelatives(mesh_shape_node, parent=1)[0])
            noDag_nodes = self.get_connected_noDag_node(mesh_shape_node, NoDagNodes)
            for node in noDag_nodes:
                if node not in used_nodes and node not in DefualtNodes:
                    used_nodes.append(node)

        unused_nodes = []
        for noDag_node in NoDagNodes:
            check_result = self.check_node(noDag_node, mesh_nodes)
            if check_result:
                if check_result not in unused_nodes:
                    unused_nodes.append(check_result)
        return unused_nodes

    def check_node(self, node, meshShape_nodes=[], checked_nodes=[]):
        if cmds.listConnections(node, d=1):
            for des_node in cmds.listConnections(node, d=1):
                if des_node in meshShape_nodes:
                    return node
                else:
                    if des_node in checked_nodes:
                        continue
                    else:
                        checked_nodes.append(node)
                        return self.check_node(des_node, meshShape_nodes, checked_nodes)
        else:
            return None

    def get_connected_noDag_node(self, node, NoDagNodes):
        get_nodes = []
        for des_node in cmds.listConnections(node, d=1, s=1):
            if des_node in NoDagNodes and des_node not in get_nodes:
                get_nodes.append(des_node)
        return get_nodes

    def check(self):
        result_proc = self.optimize_maya()
        if result_proc:
            result_log = u'Error:%s\n' % result_proc
        else:
            result_log = u'Succeed:没有问题\n'

        return result_log

    def fix(self):
        result_proc = self.optimize_maya()
        if result_proc:
            try:
                for i in result_proc:
                    if cmds.lockNode(i, q=1, l=1) == [True]:
                        cmds.lockNode(i, l=0)
                    cmds.delete(i)
                result_log = u'Succeed:%s已经删除\n' % result_proc
                return result_log
            except:
                return u'Error:%s没有删除成功\n' % result_proc
